package com.cysion.study.ui

import android.os.CountDownTimer
import android.text.Editable
import android.text.TextUtils
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.image.RoundTransform
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.HideDataUtils
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.StringUtil
import com.cysion.targetfun._subscribe
import com.xw.repo.XEditText
import kotlinx.android.synthetic.main.activity_pbind_card.*

class PBindCardActivity : BaseActivity(), View.OnClickListener {
    override fun getLayoutId(): Int {
        return R.layout.activity_pbind_card
    }

    override fun initView() {
        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            setTitle("提现账户绑定")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        et_phone.text=UserCache.userInfo?.phone!!
        tv_submit.setOnClickListener(this)
        tv_code.setOnClickListener(this)
        countTimer = CountTime(60000, 1000)


        et_bank_card.setOnXTextChangeListener(object : XEditText.OnXTextChangeListener {
            override fun afterTextChanged(s: Editable?) {
//                et_bank_card.checkBlank("请输入银行账号") ?: return

                if (s.toString().length>13) {
                    if (s.toString().length > 19) {
                        ShowToast("请输入13-19位正确的银行卡号")
                        return
                    }
                    getBankNameByNum(et_bank_card.text.toString().trim())
                }

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        })
    }

    private lateinit var countTimer: CountTime
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_code -> {
               var phone=UserCache.userInfo?.phone!!

                Alert.loading(self)
                countTimer.start()
                tv_code.isEnabled = false
                //type 类型:0.注册 1.修改登录密码 2.修改支付密码 3.登陆密码 4.修改手机号码 5、绑定手机号码 6、提现银行卡绑定
                ApiClient.api.sendCdoe(phone, "6")
                    .compose(BaseResponseRx.validateToMain())
                    ._subscribe {
                        _onNext {
                            Alert.close()
                            ShowToast("发送成功")
                        }
                        _onError {
                            if (countTimer != null) {
                                countTimer.cancel()
                            }
                            tv_code.isEnabled = true
                            tv_code.text = "获取验证码"
                            Alert.close()
                            val handle = ErrorHandler.handle(it)
                            ShowToast(handle.errorMsg)
                        }
                    }

            }
            R.id.tv_submit -> {
                var name = et_name.text.toString().trim()
                var card = et_card.text.toString().trim()
                var bankCard = et_bank_card.text.toString().trim()
                var bank = et_bank.text.toString().trim()
                var code = et_code.text.toString().trim()
                et_name.checkBlank("请输入真实姓名") ?: return
                et_card.checkBlank("请输入身份证号") ?: return
//                et_bank_card.checkBlank("请输入银行账号") ?: return
                if (et_bank_card.text.toString().trim().length < 13 || et_bank_card.text.toString().trim().length > 19) {
                    ShowToast("请输入13-19位正确的银行卡号")
                    return
                }
                et_bank.checkBlank("请输入开户支行") ?: return
                et_code.checkBlank("验证码不能为空") ?: return
                /*//教师端验证手机和验证码是否匹配
                //type 类型:0.注册 1.修改登录密码 2.修改支付密码 3.登陆密码 4.修改手机号码 5、绑定手机号码 6、提现银行卡绑定
                ApiClient.api.checkCode(phone, "6", tv_code.text.toString().trim())
                    .compose(BaseResponseRx.validateToMain())
                    ._subscribe {
                        _onNext {
                            //                        Alert.close()
                            //验证码校验成功
                            submit(name, card, bankCard, bank, code)
                        }
                        _onError {
                            //                        Alert.close()
                            val handle = ErrorHandler.handle(it)
                            ShowToast(handle.errorMsg)
                        }
                    }*/

                submit(name, card, bankCard, bank, code)


            }
        }
    }


    private fun submit(
        name: String,
        card: String,
        bankCard: String,
        bank: String,
        code: String
    ) {
        Alert.loading(this)
        ApiClient.api.addBankUpdate(name, card, bankCard, bank, code, UserCache.token).compose(
            BaseResponseRx.validateToMain()
        )
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("绑定成功")
                    finish()

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }


    //根据银行卡号获取银行名称
    private fun getBankNameByNum(bankNum: String) {

        ApiClient.api.getBankNameByNum(bankNum, UserCache.token).compose(
            BaseResponseRx.validateToMain()
        )
            ._subscribe {
                _onNext {
                    var resourceId = 0
                    println("####获取银行名称=" + it.toString())
                    if (!TextUtils.isEmpty(it.toString())) {
//
                        //支持的银行：招商银行  中国银行 工商银行 农业银行 建设银行 交通银行 其他银行
                        tv_bank_name.text =
                            it.toString() + "(" + HideDataUtils.hideCardNo(bankNum) + ")"

                        var bank = it.toString()
                        if (bank == "招商银行") {
                            rl_bank.background = resources.getDrawable(R.mipmap.icon_withdraw_bg)
                            resourceId = R.mipmap.icon_zs
                        } else if (bank == "中国银行") {
                            rl_bank.background = resources.getDrawable(R.mipmap.icon_withdraw_bg)
                            resourceId = R.mipmap.icon_zg
                        } else if (bank == "工商银行") {
                            rl_bank.background = resources.getDrawable(R.mipmap.icon_withdraw_bg)
                            resourceId = R.mipmap.icon_gs
                        } else if (bank == "农业银行") {
                            rl_bank.background = resources.getDrawable(R.mipmap.icon_ny_bg)
                            resourceId = R.mipmap.icon_ny
                        } else if (bank == "建设银行") {
                            rl_bank.background = resources.getDrawable(R.mipmap.icon_blue_bg)
                            resourceId = R.mipmap.icon_js
                        } else if (bank == "交通银行") {
                            rl_bank.background = resources.getDrawable(R.mipmap.icon_blue_bg)
                            resourceId = R.mipmap.icon_jt
                        } else if (bank == "其他银行") {
                            rl_bank.background = resources.getDrawable(R.mipmap.icon_other_bg)
                            resourceId = R.mipmap.icon_other
                        }
                    } else {
                        /*  rl_bank.visibility = View.GONE
                          ShowToast("获取银行信息失败，请输入正常的银行账号")*/
                        tv_bank_name.text =
                            it.toString() + "(" + HideDataUtils.hideCardNo(et_bank_card.text.toString().trim()) + ")"

                        rl_bank.background = resources.getDrawable(R.mipmap.icon_other_bg)
                        resourceId = R.mipmap.icon_other
                    }
                    Glide.with(self).load(resourceId)
                        .apply(RequestOptions.placeholderOf(R.mipmap.place_holder_big))
                        .apply(RequestOptions.bitmapTransform(RoundTransform(6)))
                        .into(iv_bank)
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }


    inner class CountTime : CountDownTimer {
        constructor(millisInFuture: Long, countDownInterval: Long) : super(
            millisInFuture,
            countDownInterval
        )

        override fun onFinish() {
            tv_code.isEnabled = true
            tv_code.text = "获取验证码"
        }

        override fun onTick(millisUntilFinished: Long) {
            tv_code.text = "${millisUntilFinished / 1000}秒"
        }

    }

    override fun closeMvp() {
    }
}
